package com.qingpeng.pay.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.qingpeng.pay.R;
import com.qingpeng.pay.api.Host;
import com.qingpeng.pay.api.RedBag;
import com.qingpeng.pay.base.BaseActivity;
import com.qingpeng.pay.beans.NullBean;
import com.qingpeng.pay.okhttp.RetrofitCreateHelper;
import com.qingpeng.pay.utils.APP;
import com.qingpeng.pay.utils.StringUtils;
import com.qingpeng.pay.utils.ToastUtils;
import com.qingpeng.pay.views.TitleBar;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class QRcodeActivity extends BaseActivity {
    @BindView(R.id.title)
    TitleBar title;
    @BindView(R.id.ll_weixin)
    LinearLayout llWeixin;
    @BindView(R.id.ll_alipay)
    LinearLayout llAlipay;
    @BindView(R.id.edit_home)
    EditText editHome;
    @BindView(R.id.up_image)
    ImageView upImage;
    @BindView(R.id.edit_name)
    EditText editName;
    @BindView(R.id.iamge_weixin)
    ImageView iamgeWeixin;
    @BindView(R.id.text_weixin)
    TextView textWeixin;
    @BindView(R.id.iamge_alipay)
    ImageView iamgeAlipay;
    @BindView(R.id.text_alipay)
    TextView textAlipay;
    @BindView(R.id.btn_shangma)
    LinearLayout btnShangma;
    @BindView(R.id.pay)
    TextView pay;
    private List<LocalMedia> list;
    private ArrayList<String> mStrings;
    private List<String> paths;
    private String mtype = "1";
    //读写权限
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};
    //请求状态码
    private static int REQUEST_PERMISSION_CODE = 1;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_qrcode;
    }

    @Override
    protected int getRootViewId() {
        return R.id.ll_root;
    }

    @Override
    protected int getRefreshId() {
        return 0;
    }

    @Override
    protected int getListViewId() {
        return 0;
    }


    @Override
    protected void onResume() {
        super.onResume();
        title.getLlLeft().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_PERMISSION_CODE);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CODE) {
            for (int i = 0; i < permissions.length; i++) {
                Log.i("MainActivity", "申请的权限为：" + permissions[i] + ",申请结果：" + grantResults[i]);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    list = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    for (int i = 0; i < list.size(); i++) {
                        if (list.get(i).isCompressed()) {
                            paths = new ArrayList<>();
                            paths.add(list.get(i).getCompressPath());
                            Glide.with(this).load(paths.get(i)).into(upImage);
                            upImage.setVisibility(View.VISIBLE);
                            btnShangma.setVisibility(View.GONE);
                        }
                    }
                    break;
            }
        }
    }

    private void show() {
        // 进入相册 以下是例子：用不到的api可以不写
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .imageSpanCount(4)// 每行显示个数 int
                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                .previewImage(true)// 是否可预览图片 true or false
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                .compress(true)// 是否压缩 true or false
                .selectionMedia(list)// 是否传入已选图片 List<LocalMedia> list
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .synOrAsy(true)//同步true或异步false 压缩 默认同步
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

    @OnClick({R.id.up_image, R.id.ll_weixin, R.id.ll_alipay, R.id.btn_shangma, R.id.pay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.up_image:
                show();
                break;
            case R.id.ll_weixin:
                mtype = "1";
                break;
            case R.id.ll_alipay:
                ToastUtils.showToast(QRcodeActivity.this, "暂未开放");
                break;
            case R.id.btn_shangma:
                show();
                break;
            case R.id.pay:
                if (StringUtils.isEmpty(editName.getText().toString())&&StringUtils.isEmpty(editHome.getText().toString())){
                    ToastUtils.showToast(QRcodeActivity.this,"请填写详细信息");
                    return;
                }
                HashMap<String, RequestBody> map = new HashMap<>();
                final MultipartBody.Part[] parts = new MultipartBody.Part[paths.size()];
                for (String imgPath : paths) {
                    final File file = new File(imgPath);
                    map.put("uploadfile[]\"; filename=\"" + file.getName(), RequestBody.create(MediaType.parse("image/*"), file));
                }
                // create a map of data to pass along
                RequestBody tokenBody = RequestBody.create(
                        MediaType.parse("multipart/form-data"), APP.uid);
                RequestBody name = RequestBody.create(
                        MediaType.parse("multipart/form-data"), editName.getText().toString());
                RequestBody home = RequestBody.create(
                        MediaType.parse("multipart/form-data"), editHome.getText().toString());
                RequestBody type = RequestBody.create(
                        MediaType.parse("multipart/form-data"), mtype);
                map.put("user_id", tokenBody);
                map.put("name", name);
                map.put("home", home);
                map.put("type", type);
//实测，zyp传过去的值有引号"zyp"，所以要用body传值
                pay.setClickable(false);
                Call<NullBean> responseBodyCall = RetrofitCreateHelper.createApi(RedBag.class, Host.HOST).imageUpload(map);
                responseBodyCall.enqueue(new Callback<NullBean>() {
                    @Override
                    public void onResponse(Call<NullBean> call, Response<NullBean> response) {
                        if (response.body().getStatus() != 1) {
                            ToastUtils.showToast(QRcodeActivity.this, response.body().getInfo());
                            pay.setClickable(true);
                            return;
                        }
                        pay.setClickable(true);
                        ToastUtils.showToast(QRcodeActivity.this, "上传成功");
                        finish();
                    }

                    @Override
                    public void onFailure(Call<NullBean> call, Throwable t) {
                        ToastUtils.showToast(QRcodeActivity.this, "上传失败");
                        list.clear();
                        paths.clear();
                        pay.setClickable(true);
                    }
                });
                break;
        }
    }
}
